home *** CD-ROM | disk | FTP | other *** search
/ Atari Mega Archive 1 / Atari Mega Archive - Volume 1.iso / gnu / bash / bash_110 / mint / bash110s.zoo / bash-1.10 / execute_cmd.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-10-03  |  74.3 KB  |  2,772 lines

  1. /* execute_command.c -- Execute a COMMAND structure. */
  2.  
  3. /* Copyright (C) 1987,1991 Free Software Foundation, Inc.
  4.  
  5.    This file is part of GNU Bash, the Bourne Again SHell.
  6.  
  7.    Bash is free software; you can redistribute it and/or modify it
  8.    under the terms of the GNU General Public License as published by
  9.    the Free Software Foundation; either version 1, or (at your option)
  10.    any later version.
  11.  
  12.    Bash is distributed in the hope that it will be useful, but WITHOUT
  13.    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  14.    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
  15.    License for more details.
  16.  
  17.    You should have received a copy of the GNU General Public License
  18.    along with Bash; see the file COPYING.  If not, write to the Free
  19.    Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
  20.  
  21. #include <stdio.h>
  22. #include <ctype.h>
  23. #include <sys/types.h>
  24. #include <sys/file.h>
  25. #include "posixstat.h"
  26. #include "filecntl.h"
  27. #include <signal.h>
  28.  
  29. #if !defined (SIGABRT)
  30. #define SIGABRT SIGIOT
  31. #endif
  32.  
  33. #include <sys/param.h>
  34. #include <errno.h>
  35.  
  36. #include "shell.h"
  37. #include "y.tab.h"
  38. #include "flags.h"
  39. #include "hash.h"
  40. #include "jobs.h"
  41.  
  42. #include "sysdefs.h"
  43.  
  44. #if defined (USE_GLOB_LIBRARY)
  45. #  include <glob/glob.h>
  46. #else
  47. #  define FNM_NOMATCH 1
  48. #endif /* USE_GLOB_LIBRARY */
  49.  
  50. int builtin_pipe_in = NO_PIPE;
  51. int builtin_pipe_out = NO_PIPE;
  52.  
  53. #if !defined (errno)
  54. extern int errno;
  55. #endif
  56.  
  57. extern int breaking, continuing, loop_level;
  58. extern int interactive, login_shell;
  59.  
  60. #if defined (JOB_CONTROL)
  61. extern int job_control;
  62. extern int set_job_control ();
  63. #endif /* JOB_CONTROL */
  64.  
  65. extern int getdtablesize ();
  66. extern int close ();
  67. extern char *strerror ();
  68. extern char *string_list ();
  69.  
  70. #if defined (USG)
  71. extern pid_t last_made_pid;
  72. #endif
  73.  
  74. extern WORD_LIST *expand_words (), *expand_word ();
  75. extern char *make_command_string ();
  76.  
  77. extern Function *find_shell_builtin ();
  78.  
  79. /* Static functions defined and used in this file. */
  80. static void close_pipes (), close_all_files ();
  81. static void do_piping ();
  82. static int do_redirection_internal (), do_redirections ();
  83. static int expandable_redirection_filename ();
  84. static int execute_shell_script ();
  85. static void execute_disk_command ();
  86. static int execute_builtin_or_function ();
  87. static void execute_subshell_builtin_or_function ();
  88. static void cleanup_redirects (), cleanup_func_redirects ();
  89. static void bind_lastarg ();
  90. static int add_undo_redirect ();
  91. static void add_undo_close_redirect ();
  92. static char *find_user_command_internal ();
  93. static char *find_user_command_in_path ();
  94.  
  95. /* The value returned by the last synchronous command. */
  96. int last_command_exit_value = 0;
  97.  
  98. /* The list of redirections to preform which will undo the redirections
  99.    that I made in the shell. */
  100. REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
  101.  
  102. /* Use this as the function to call when adding unwind protects so we
  103.    don't need to know what free() returns. */
  104. static void
  105. vfree(s)
  106.      char *s;
  107. {
  108.   free (s);
  109. }
  110.  
  111. #define FD_BITMAP_DEFAULT_SIZE 32
  112. /* Functions to allocate and deallocate the structures used to pass
  113.    information from the shell to its children about file descriptors
  114.    to close. */
  115. struct fd_bitmap *
  116. new_fd_bitmap (size)
  117.      long size;
  118. {
  119.   struct fd_bitmap *ret;
  120.  
  121.   ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
  122.  
  123.   ret->size = size;
  124.  
  125.   if (size)
  126.     {
  127.       ret->bitmap = (char *)xmalloc (size);
  128.       bzero (ret->bitmap, size);
  129.     }
  130.   else
  131.     ret->bitmap = (char *)NULL;
  132.   return (ret);
  133. }
  134.  
  135. void
  136. dispose_fd_bitmap (fdbp)
  137.      struct fd_bitmap *fdbp;
  138. {
  139.   if (fdbp->bitmap)
  140.     free (fdbp->bitmap);
  141.  
  142.   free (fdbp);
  143. }
  144.  
  145. void
  146. close_fd_bitmap (fdbp)
  147.      struct fd_bitmap *fdbp;
  148. {
  149.   register int i;
  150.  
  151.   if (fdbp)
  152.     {
  153.       for (i = 0; i < fdbp->size; i++)
  154.     if (fdbp->bitmap[i])
  155.       {
  156.         close (i);
  157.         fdbp->bitmap[i] = 0;
  158.       }
  159.     }
  160. }
  161.  
  162. /* Execute the command passed in COMMAND.  COMMAND is exactly what
  163.    read_command () places into GLOBAL_COMMAND.  See "shell.h" for the
  164.    details of the command structure.
  165.  
  166.    EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
  167.    return values.  Executing a command with nothing in it returns
  168.    success. */
  169. execute_command (command)
  170.      COMMAND *command;
  171. {
  172.   struct fd_bitmap *fd_close_bmap;
  173.   int r;
  174.  
  175.   fd_close_bmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
  176.  
  177.   /* Just do the command, but not asynchronously. */
  178.   r = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, fd_close_bmap);
  179.   dispose_fd_bitmap (fd_close_bmap);
  180.  
  181. #if defined (PROCESS_SUBSTITUTION)
  182.   unlink_fifo_list ();
  183. #endif
  184.  
  185.   return r;
  186. }
  187.  
  188. /* Returns 1 if TYPE is a shell control structure type. */
  189. int
  190. shell_control_structure (type)
  191.      enum command_type type;
  192. {
  193.   switch (type)
  194.     {
  195.     case cm_for:
  196.     case cm_case:
  197.     case cm_while:
  198.     case cm_until:
  199.     case cm_if:
  200.     case cm_group:
  201.       return (1);
  202.  
  203.     default:
  204.       return (0);
  205.     }
  206. }
  207.  
  208. /* A function to use to unwind_protect the redirection undo list
  209.    for loops. */
  210. static void
  211. cleanup_redirects (list)
  212.      REDIRECT *list;
  213. {
  214.   do_redirections (list, 1, 0, 0);
  215.   dispose_redirects (list);
  216. }
  217.  
  218. /* Function to unwind_protect the redirections for functions and builtins. */
  219. static void
  220. cleanup_func_redirects (list)
  221.      REDIRECT *list;
  222. {
  223.   do_redirections (list, 1, 0, 0);
  224. }
  225.  
  226. #if defined (JOB_CONTROL)
  227. /* A function to restore the signal mask to its proper value when the shell
  228.    is interrupted or errors occur while creating a pipeline. */
  229. static int
  230. restore_signal_mask (set)
  231.      sigset_t set;
  232. {
  233.   return (sigprocmask (SIG_SETMASK, &set, (sigset_t *)NULL));
  234. }
  235. #endif /* JOB_CONTROL */
  236.  
  237. /* A debugging function that can be called from gdb, for instance. */
  238. open_files ()
  239. {
  240.   register int i;
  241.   int f, fd_table_size;
  242.  
  243.   fd_table_size = getdtablesize ();
  244.  
  245.   fprintf (stderr, "pid %d open files:", getpid ());
  246.   for (i = 3; i < fd_table_size; i++)
  247.     {
  248.       if ((f = fcntl (i, F_GETFD, 0)) != -1)
  249.     fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
  250.     }
  251.   fprintf (stderr, "\n");
  252. }
  253.  
  254. execute_command_internal (command, asynchronous, pipe_in, pipe_out, 
  255.               fds_to_close)
  256.      COMMAND *command;
  257.      int asynchronous;
  258.      int pipe_in, pipe_out;
  259.      struct fd_bitmap *fds_to_close;
  260. {
  261.   int exec_result = EXECUTION_SUCCESS;
  262.   int invert, ignore_return;
  263. #if defined (JOB_CONTROL)
  264.   int old_job_control;
  265. #endif
  266.   REDIRECT *my_undo_list;
  267.  
  268.   if (!command || breaking || continuing)
  269.     return (EXECUTION_SUCCESS);
  270.  
  271.   run_pending_traps ();
  272.  
  273.   invert = (command->flags & CMD_INVERT_RETURN) != 0;
  274.  
  275.   /* If a command was being explicitly run in a subshell, or if it is
  276.      a shell control-structure, and it has a pipe, then we do the command
  277.      in a subshell. */
  278.  
  279.   if ((command->flags & CMD_WANT_SUBSHELL) ||
  280.       (command->flags & CMD_FORCE_SUBSHELL)  ||
  281.       (shell_control_structure (command->type) &&
  282.        (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
  283.     {
  284.       pid_t paren_pid;
  285.  
  286.       /* Fork a subshell, turn off the subshell bit, turn off job
  287.      control and call execute_command () on the command again. */
  288.       paren_pid = make_child (savestring (make_command_string (command)),
  289.                   asynchronous);
  290.       if (paren_pid == 0)
  291.     {
  292.       int user_subshell, return_code;
  293.  
  294.       user_subshell = (command->flags & CMD_WANT_SUBSHELL) != 0;
  295.       command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL);
  296.  
  297.       /* If a command is asynchronous in a subshell (like ( foo ) & or
  298.          the special case of an asynchronous GROUP command where the
  299.          the subshell bit is turned on down in case cm_group: below), 
  300.          turn off `asynchronous', so that two subshells aren't spawned.
  301.  
  302.          This seems semantically correct to me.  For example, 
  303.          ( foo ) & seems to say ``do the command `foo' in a subshell
  304.          environment, but don't wait for that subshell to finish'',
  305.          and "{ foo ; bar } &" seems to me to be like functions or
  306.          builtins in the background, which executed in a subshell
  307.          environment.  I just don't see the need to fork two subshells. */
  308.  
  309.       /* Don't fork again, we are already in a subshell. */
  310.       asynchronous = 0;
  311.  
  312.       /* Subshells are neither login nor interactive. */
  313.       login_shell = interactive = 0;
  314.  
  315. #if defined (JOB_CONTROL)
  316.       /* Delete all traces that there were any jobs running.  This is
  317.          only for subshells. */
  318.       without_job_control ();
  319. #endif /* JOB_CONTROL */
  320.       do_piping (pipe_in, pipe_out);
  321.  
  322.       if (fds_to_close)
  323.         close_fd_bitmap (fds_to_close);
  324.  
  325.       if (command->redirects)
  326.         if (!(do_redirections (command->redirects, 1, 0, 0) == 0))
  327.           exit (EXECUTION_FAILURE);
  328.  
  329.       return_code = execute_command_internal
  330.         (command, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
  331.  
  332.       /* If we were explicitly placed in a subshell with (), we need
  333.          to do the `shell cleanup' things, such as running traps[0]. */
  334.       if (user_subshell)
  335.         run_exit_trap ();
  336.  
  337.       exit (return_code);
  338.     }
  339.       else
  340.     {
  341.       close_pipes (pipe_in, pipe_out);
  342.  
  343.       /* If we are part of a pipeline, and not the end of the pipeline,
  344.          then we should simply return and let the last command in the
  345.          pipe be waited for.  If we are not in a pipeline, or are the
  346.          last command in the pipeline, then we wait for the subshell 
  347.          and return its exit status as usual. */
  348.       if (pipe_out != NO_PIPE)
  349.         return (EXECUTION_SUCCESS);
  350.  
  351.       stop_pipeline (asynchronous, (COMMAND *)NULL);
  352.  
  353.       if (!asynchronous)
  354.         {
  355.           last_command_exit_value = wait_for (paren_pid);
  356.  
  357.           /* If we have to, invert the return value. */
  358.           if (invert)
  359.         {
  360.           if (last_command_exit_value == EXECUTION_SUCCESS)
  361.             return (EXECUTION_FAILURE);
  362.           else
  363.             return (EXECUTION_SUCCESS);
  364.         }
  365.           else
  366.         return (last_command_exit_value);
  367.         }
  368.       else
  369.         {
  370.           if (interactive)
  371.         describe_pid (paren_pid);
  372.  
  373.           run_pending_traps ();
  374.  
  375.           return (EXECUTION_SUCCESS);
  376.         }
  377.     }
  378.     }
  379.  
  380.   /* Handle WHILE FOR CASE etc. with redirections.  (Also '&' input
  381.      redirection.)  */
  382.   do_redirections (command->redirects, 1, 1, 0);
  383.   my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
  384.  
  385.   begin_unwind_frame ("loop_redirections");
  386.  
  387.   if (my_undo_list)
  388.     add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
  389.  
  390.   ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
  391.  
  392.   switch (command->type)
  393.     {
  394.     case cm_for:
  395.       if (ignore_return)
  396.     command->value.For->flags |= CMD_IGNORE_RETURN;
  397.       exec_result = execute_for_command (command->value.For);
  398.       break;
  399.  
  400.     case cm_case:
  401.       if (ignore_return)
  402.     command->value.Case->flags |= CMD_IGNORE_RETURN;
  403.       exec_result = execute_case_command (command->value.Case);
  404.       break;
  405.  
  406.     case cm_while:
  407.       if (ignore_return)
  408.     command->value.While->flags |= CMD_IGNORE_RETURN;
  409.       exec_result = execute_while_command (command->value.While);
  410.       break;
  411.  
  412.     case cm_until:
  413.       if (ignore_return)
  414.     command->value.While->flags |= CMD_IGNORE_RETURN;
  415.       exec_result = execute_until_command (command->value.While);
  416.       break;
  417.  
  418.     case cm_if:
  419.       if (ignore_return)
  420.     command->value.If->flags |= CMD_IGNORE_RETURN;
  421.       exec_result = execute_if_command (command->value.If);
  422.       break;
  423.  
  424.     case cm_group:
  425.  
  426.       /* This code can be executed from either of two paths: an explicit
  427.      '{}' command, or via a function call.  If we are executed via a
  428.      function call, we have already taken care of the function being
  429.      executed in the background (down there in execute_simple_command ()),
  430.      and this command should *not* be marked as asynchronous.  If we
  431.      are executing a regular '{}' group command, and asynchronous == 1,
  432.      we must want to execute the whole command in the background, so we
  433.      need a subshell, and we want the stuff executed in that subshell
  434.      (this group command) to be executed in the foreground of that
  435.      subshell (i.e. there will not be *another* subshell forked).
  436.  
  437.      What we do is to force a subshell if asynchronous, and then call
  438.      execute_command_internal again with asynchronous still set to 1,
  439.      but with the original group command, so the printed command will
  440.      look right.
  441.  
  442.      The code above that handles forking off subshells will note that
  443.      both subshell and async are on, and turn off async in the child
  444.      after forking the subshell (but leave async set in the parent, so
  445.      the normal call to describe_pid is made).  This turning off
  446.      async is *crucial*; if it is not done, this will fall into an
  447.      infinite loop of executions through this spot in subshell after
  448.      subshell until the process limit is exhausted. */
  449.  
  450.       if (asynchronous)
  451.     {
  452.       command->flags |= CMD_FORCE_SUBSHELL;
  453.       exec_result =
  454.         execute_command_internal (command, 1, pipe_in, pipe_out,
  455.                       fds_to_close);
  456.     }
  457.       else
  458.     {
  459.       if (ignore_return && command->value.Group->command)
  460.         command->value.Group->command->flags |= CMD_IGNORE_RETURN;
  461.       exec_result =
  462.         execute_command_internal (command->value.Group->command,
  463.                       asynchronous, pipe_in, pipe_out,
  464.                       fds_to_close);
  465.     }
  466.       break;
  467.  
  468.     case cm_simple:
  469.       {
  470.     pid_t last_pid = last_made_pid;
  471.  
  472. #if defined (JOB_CONTROL)
  473.     extern int already_making_children;
  474. #endif /* JOB_CONTROL */
  475.     if (ignore_return && command->value.Simple)
  476.       command->value.Simple->flags |= CMD_IGNORE_RETURN;
  477.     exec_result =
  478.       execute_simple_command (command->value.Simple, pipe_in, pipe_out,
  479.                   asynchronous, fds_to_close);
  480.  
  481.     /* The temporary environment should be used for only the simple
  482.        command immediately following its definition. */
  483.     dispose_used_env_vars ();
  484.  
  485.     /* If we forked to do the command, then we must
  486.        wait_for() the child. */
  487. #if defined (JOB_CONTROL)
  488.     if (already_making_children && pipe_out == NO_PIPE)
  489. #else
  490.       if (pipe_out == NO_PIPE)
  491. #endif /* JOB_CONTROL */
  492.         {
  493.           if (last_pid != last_made_pid)
  494.         {
  495.           stop_pipeline (asynchronous, (COMMAND *)NULL);
  496.  
  497.           if (asynchronous)
  498.             {
  499.               if (interactive)
  500.             describe_pid (last_made_pid);
  501.             }
  502.           else
  503. #if !defined (JOB_CONTROL)
  504.             /* Do not wait for asynchronous processes started from
  505.                startup files. */
  506.             if (last_made_pid != last_asynchronous_pid)
  507. #endif
  508.               /* When executing a shell function that executes other
  509.              commands, this causes the last simple command in
  510.              the function to be waited for twice. */
  511.               exec_result = wait_for (last_made_pid);
  512.         }
  513.         }
  514.       }
  515.       if (!ignore_return && exit_immediately_on_error && !invert &&
  516.       (exec_result != EXECUTION_SUCCESS))
  517.     {
  518.       last_command_exit_value = exec_result;
  519.       run_pending_traps ();
  520.       longjmp (top_level, EXITPROG);
  521.     }
  522.  
  523.       break;
  524.  
  525.     case cm_connection:
  526.       switch (command->value.Connection->connector)
  527.     {
  528.       /* Do the first command asynchronously. */
  529.     case '&':
  530.       {
  531.         COMMAND *tc = command->value.Connection->first;
  532.         if (ignore_return && tc)
  533.           tc->flags |= CMD_IGNORE_RETURN;
  534.  
  535. #if !defined (JOB_CONTROL)
  536.         {
  537.           REDIRECT *tr = 
  538.         make_redirection (0, r_inputa_direction,
  539.                   make_word ("/dev/null"));
  540.           tr->next = tc->redirects;
  541.           tc->redirects = tr;
  542.         }
  543. #endif /* !JOB_CONTROL */
  544.         exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out,
  545.                             fds_to_close);
  546.         if (command->value.Connection->second)
  547.           {
  548.         if (ignore_return && command->value.Connection->second)
  549.           command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
  550.  
  551.         exec_result =
  552.           execute_command_internal (command->value.Connection->second,
  553.                         asynchronous, pipe_in, pipe_out,
  554.                         fds_to_close);
  555.           }
  556.       }
  557.       break;
  558.  
  559.     case ';':
  560.       /* Just call execute command on both of them. */
  561.       if (ignore_return)
  562.         {
  563.           if (command->value.Connection->first)
  564.         command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
  565.           if (command->value.Connection->second)
  566.         command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
  567.         }
  568.       execute_command (command->value.Connection->first);
  569.       exec_result =
  570.         execute_command_internal (command->value.Connection->second,
  571.                       asynchronous, pipe_in, pipe_out,
  572.                       fds_to_close);
  573.       break;
  574.  
  575.     case '|':
  576.       {
  577.         int prev, fildes[2], new_bitmap_size, dummyfd;
  578.         COMMAND *cmd;
  579.         struct fd_bitmap *fd_bitmap;
  580.  
  581. #if defined (JOB_CONTROL)
  582.         sigset_t set, oset;
  583.         BLOCK_CHILD (set, oset);
  584. #endif /* JOB_CONTROL */
  585.  
  586.         prev = pipe_in;
  587.         cmd = command;
  588.  
  589.         while (cmd &&
  590.            cmd->type == cm_connection &&
  591.            cmd->value.Connection &&
  592.            cmd->value.Connection->connector == '|')
  593.           {
  594.         /* Make a pipeline between the two commands. */
  595.         if (pipe (fildes) < 0)
  596.           {
  597.             report_error ("pipe error: %s", strerror (errno));
  598. #if defined (JOB_CONTROL)
  599.             terminate_current_pipeline ();
  600.             kill_current_pipeline ();
  601. #endif /* JOB_CONTROL */
  602.             last_command_exit_value = EXECUTION_FAILURE;
  603.             /* The unwind-protects installed below will take care
  604.                of closing all of the open file descriptors. */
  605.             throw_to_top_level ();
  606.           }
  607.         else
  608.           {
  609.             /* Here is a problem: with the new file close-on-exec
  610.                code, the read end of the pipe (fildes[0]) stays open
  611.                in the first process, so that process will never get a
  612.                SIGPIPE.  There is no way to signal the first process
  613.                that it should close fildes[0] after forking, so it
  614.                remains open.  No SIGPIPE is ever sent because there
  615.                is still a file descriptor open for reading connected
  616.                to the pipe.  We take care of that here.  This passes
  617.                around a bitmap of file descriptors that must be
  618.                closed after making a child process in
  619.                execute_simple_command. */
  620.  
  621.             /* We need fd_bitmap to be at least as big as fildes[0].
  622.                If fildes[0] is less than fds_to_close->size, then
  623.                use fds_to_close->size. */
  624.  
  625.             if (fildes[0] < fds_to_close->size)
  626.               new_bitmap_size = fds_to_close->size;
  627.             else
  628.               new_bitmap_size = fildes[0] + 8;
  629.  
  630.             fd_bitmap = new_fd_bitmap (new_bitmap_size);
  631.  
  632.             /* Now copy the old information into the new bitmap. */
  633.             bcopy (fds_to_close->bitmap, fd_bitmap->bitmap,
  634.                fds_to_close->size);
  635.  
  636.             /* And mark the pipe file descriptors to be closed. */
  637.             fd_bitmap->bitmap[fildes[0]] = 1;
  638.  
  639.             /* In case there are pipe or out-of-processes errors, we
  640.                want all these file descriptors to be closed when
  641.                unwind-protects are run, and the storage used for the
  642.                bitmaps freed up. */
  643.             begin_unwind_frame ("pipe-file-descriptors");
  644.             add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
  645.             add_unwind_protect (close_fd_bitmap, fd_bitmap);
  646.             if (prev >= 0)
  647.               add_unwind_protect (close, prev);
  648.             dummyfd = fildes[1];
  649.             add_unwind_protect (close, dummyfd);
  650.  
  651. #if defined (JOB_CONTROL)
  652.             add_unwind_protect (restore_signal_mask, oset);
  653. #endif /* JOB_CONTROL */
  654.  
  655.             if (ignore_return && cmd->value.Connection->first)
  656.               cmd->value.Connection->first->flags |=
  657.             CMD_IGNORE_RETURN;
  658.             execute_command_internal
  659.               (cmd->value.Connection->first, asynchronous, prev,
  660.                fildes[1], fd_bitmap);
  661.  
  662.             if (prev >= 0)
  663.               close (prev);
  664.             
  665.             prev = fildes[0];
  666.             close (fildes[1]);
  667.  
  668.             dispose_fd_bitmap (fd_bitmap);
  669.             discard_unwind_frame ("pipe-file-descriptors");
  670.           }
  671.         cmd = cmd->value.Connection->second;
  672.           }
  673.  
  674.         /* Now execute the rightmost command in the pipeline.  */
  675.         if (ignore_return && cmd)
  676.           cmd->flags |= CMD_IGNORE_RETURN;
  677.         exec_result =
  678.           execute_command_internal
  679.         (cmd, asynchronous, prev, pipe_out, fds_to_close);
  680.  
  681.         if (prev >= 0)
  682.           close (prev);
  683.  
  684. #if defined (JOB_CONTROL)
  685.         UNBLOCK_CHILD (oset);
  686. #endif
  687.       }
  688.       break;
  689.  
  690.     case AND_AND:
  691.       if (asynchronous)
  692.         {
  693.           /* If we have something like `a && b &', run the && stuff in a
  694.          subshell.  Force a subshell and just call
  695.          execute_command_internal again.  Leave asynchronous on
  696.          so that we get a report from the parent shell about the
  697.          background job. */
  698.           command->flags |= CMD_FORCE_SUBSHELL;
  699.           exec_result = execute_command_internal (command, 1, pipe_in,
  700.                   pipe_out, fds_to_close);
  701.           break;
  702.         }
  703.  
  704.       /* Execute the first command.  If the result of that is successful,
  705.          then execute the second command, otherwise return. */
  706. #if defined (JOB_CONTROL)
  707.       begin_unwind_frame ("and-and");
  708.       old_job_control = set_job_control (0);
  709.       add_unwind_protect (set_job_control, old_job_control);
  710. #endif /* JOB_CONTROL */
  711.  
  712.       if (command->value.Connection->first)
  713.         command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
  714.  
  715.       exec_result = execute_command (command->value.Connection->first);
  716.       if (exec_result == EXECUTION_SUCCESS)
  717.         {
  718.           if (ignore_return && command->value.Connection->second)
  719.         command->value.Connection->second->flags |=
  720.           CMD_IGNORE_RETURN;
  721.  
  722.           exec_result =
  723.         execute_command (command->value.Connection->second);
  724.         }
  725.  
  726. #if defined (JOB_CONTROL)
  727.       run_unwind_frame ("and-and");
  728. #endif /* JOB_CONTROL */
  729.       break;
  730.  
  731.     case OR_OR:
  732.       if (asynchronous)
  733.         {
  734.           /* If we have something like `a || b &', run the || stuff in a
  735.          subshell.  Force a subshell and just call
  736.          execute_command_internal again.  Leave asynchronous on
  737.          so that we get a report from the parent shell about the
  738.          background job. */
  739.           command->flags |= CMD_FORCE_SUBSHELL;
  740.           exec_result = execute_command_internal (command, 1, pipe_in,
  741.                   pipe_out, fds_to_close);
  742.           break;
  743.         }
  744.  
  745.       /* Execute the first command.  If the result of that is successful,
  746.          then return, otherwise execute the second command. */
  747. #if defined (JOB_CONTROL)
  748.       begin_unwind_frame ("or-or");
  749.       old_job_control = set_job_control (0);
  750.       add_unwind_protect (set_job_control, old_job_control);
  751. #endif
  752.  
  753.       if (command->value.Connection->first)
  754.         command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
  755.  
  756.       exec_result = execute_command (command->value.Connection->first);
  757.       if (exec_result != EXECUTION_SUCCESS)
  758.         {
  759.           if (ignore_return && command->value.Connection->second)
  760.         command->value.Connection->second->flags |=
  761.           CMD_IGNORE_RETURN;
  762.  
  763.           exec_result =
  764.         execute_command (command->value.Connection->second);
  765.         }
  766.  
  767. #if defined (JOB_CONTROL)
  768.       run_unwind_frame ("or-or");
  769. #endif /* JOB_CONTROL */
  770.       break;
  771.  
  772.     default:
  773.       programming_error ("Bad connector `%d'!",
  774.                  command->value.Connection->connector);
  775.       longjmp (top_level, DISCARD);
  776.       break;
  777.     }
  778.       break;
  779.  
  780.     case cm_function_def:
  781.       exec_result = intern_function (command->value.Function_def->name,
  782.                      command->value.Function_def->command);
  783.       break;
  784.  
  785.     default:
  786.       programming_error ("execute_command: Bad command type `%d'!",
  787.              command->type);
  788.     }
  789.  
  790.   if (my_undo_list)
  791.     {
  792.       do_redirections (my_undo_list, 1, 0, 0);
  793.       dispose_redirects (my_undo_list);
  794.     }
  795.  
  796.   discard_unwind_frame ("loop_redirections");
  797.  
  798.   /* Invert the return value if we have to */
  799.   if (invert)
  800.     {
  801.       if (exec_result == EXECUTION_SUCCESS)
  802.     exec_result = EXECUTION_FAILURE;
  803.       else
  804.     exec_result = EXECUTION_SUCCESS;
  805.     }
  806.  
  807.   last_command_exit_value = exec_result;
  808.   run_pending_traps ();
  809.   return (last_command_exit_value);
  810. }
  811.  
  812. /* Execute a FOR command.  The syntax is: FOR word_desc IN word_list;
  813.    DO command; DONE */
  814. execute_for_command (for_command)
  815.      FOR_COM *for_command;
  816. {
  817.   /* I just noticed that the Bourne shell leaves word_desc bound to the
  818.      last name in word_list after the FOR statement is done.  This seems
  819.      wrong to me; I thought that the variable binding should be lexically
  820.      scoped, i.e., only would last the duration of the FOR command.  This
  821.      behaviour can be gotten by turning on the lexical_scoping switch. */
  822.  
  823.   register WORD_LIST *releaser, *list;
  824.   WORD_DESC *temp = for_command->name;
  825.   char *identifier;
  826.   SHELL_VAR *old_value;        /* Remember the old value of x. */
  827.   int retval = EXECUTION_SUCCESS;
  828.   extern int dispose_words ();
  829.   extern int dispose_variable ();
  830.  
  831.   if (!check_identifier (temp))
  832.     return (EXECUTION_FAILURE);
  833.  
  834.   loop_level++;
  835.   identifier = temp->word;
  836.  
  837.   list = releaser = expand_words (for_command->map_list, 0);
  838.  
  839.   begin_unwind_frame ("for");
  840.   add_unwind_protect (dispose_words, releaser);
  841.  
  842.   if (lexical_scoping)
  843.     {
  844.       old_value = copy_variable (find_variable (identifier));
  845.       if (old_value)
  846.     add_unwind_protect (dispose_variable, old_value);
  847.     }
  848.  
  849.   while (list)
  850.     {
  851.       QUIT;
  852.       bind_variable (identifier, list->word->word);
  853.       if (for_command->flags & CMD_IGNORE_RETURN)
  854.     for_command->action->flags |= CMD_IGNORE_RETURN;
  855.       execute_command (for_command->action);
  856.       retval = last_command_exit_value;
  857.       QUIT;
  858.  
  859.       if (breaking)
  860.     {
  861.       breaking--; 
  862.       break;
  863.     }
  864.  
  865.       if (continuing)
  866.     {
  867.       continuing--;
  868.       if (continuing)
  869.         break;
  870.     }
  871.  
  872.       list = list->next;
  873.     }
  874.  
  875.   loop_level--;
  876.  
  877.   if (lexical_scoping)
  878.     {
  879.       if (!old_value)
  880.     makunbound (identifier, shell_variables);
  881.       else
  882.     {
  883.       SHELL_VAR *new_value;
  884.  
  885.       new_value = bind_variable (identifier, value_cell(old_value));
  886.       new_value->attributes = old_value->attributes;
  887.     }
  888.     }
  889.  
  890.   run_unwind_frame ("for");
  891.   return (retval);
  892. }
  893.  
  894. /* Execute a CASE command.  The syntax is: CASE word_desc IN pattern_list ESAC.
  895.    The pattern_list is a linked list of pattern clauses; each clause contains
  896.    some patterns to compare word_desc against, and an associated command to
  897.    execute. */
  898. execute_case_command (case_command)
  899.      CASE_COM *case_command;
  900. {
  901.   extern int dispose_words ();
  902.  
  903.   register WORD_LIST *list;
  904.   WORD_LIST *wlist;
  905.   PATTERN_LIST *clauses;
  906.   char *word;
  907.   int retval;
  908.  
  909.   wlist = expand_word (case_command->word, 0);
  910.   clauses = case_command->clauses;
  911.   word = (wlist) ? string_list (wlist) : savestring ("");
  912.   retval = EXECUTION_SUCCESS;
  913.  
  914.   begin_unwind_frame ("case");
  915.   add_unwind_protect (dispose_words, wlist);
  916.   add_unwind_protect ((Function *)vfree, word);
  917.  
  918.   while (clauses)
  919.     {
  920.       QUIT;
  921.       list = clauses->patterns;
  922.       while (list)
  923.     {
  924.       WORD_LIST *es = expand_word (list->word, 0);
  925.       char *pattern = (es) ? es->word->word : "";
  926.  
  927.       if (fnmatch (pattern, word, 0) != FNM_NOMATCH)
  928.         {
  929.           dispose_words (es);
  930.           if (clauses->action && 
  931.           (case_command->flags & CMD_IGNORE_RETURN))
  932.         clauses->action->flags |= CMD_IGNORE_RETURN;
  933.           execute_command (clauses->action);
  934.           retval = last_command_exit_value;
  935.           goto exit_command;
  936.         }
  937.       dispose_words (es);
  938.       list = list->next;
  939.       QUIT;
  940.     }
  941.       clauses = clauses->next;
  942.     }
  943.  exit_command:
  944.   run_unwind_frame ("case");
  945.   return (retval);
  946. }
  947.  
  948. #define CMD_WHILE 0
  949. #define CMD_UNTIL 1
  950.  
  951. /* The WHILE command.  Syntax: WHILE test DO action; DONE.
  952.    Repeatedly execute action while executing test produces
  953.    EXECUTION_SUCCESS. */
  954. execute_while_command (while_command)
  955.      WHILE_COM *while_command;
  956. {
  957.   return (execute_while_or_until (while_command, CMD_WHILE));
  958. }
  959.  
  960. /* UNTIL is just like WHILE except that the test result is negated. */
  961. execute_until_command (while_command)
  962.      WHILE_COM *while_command;
  963. {
  964.   return (execute_while_or_until (while_command, CMD_UNTIL));
  965. }
  966.  
  967. /* The body for both while and until.  The only difference between the
  968.    two is that the test value is treated differently.  TYPE is
  969.    CMD_WHILE or CMD_UNTIL.  The return value for both commands should
  970.    be EXECUTION_SUCCESS if no commands in the body are executed, and
  971.    the status of the last command executed in the body otherwise. */
  972. execute_while_or_until (while_command, type)
  973.      WHILE_COM *while_command;
  974.      int type;
  975. {
  976.   extern int breaking;
  977.   extern int continuing;
  978.   int commands_executed = 0;
  979.   int return_value;
  980.  
  981.   loop_level++;
  982.   while_command->test->flags |= CMD_IGNORE_RETURN;
  983.  
  984.   while (1)
  985.     {
  986.       return_value = execute_command (while_command->test);
  987.  
  988.       if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
  989.     break;
  990.       if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
  991.     break;
  992.  
  993.       QUIT;
  994.       commands_executed = 1;
  995.  
  996.       if (while_command->flags & CMD_IGNORE_RETURN)
  997.     while_command->action->flags |= CMD_IGNORE_RETURN;
  998.       execute_command (while_command->action);
  999.  
  1000.       QUIT;
  1001.  
  1002.       if (breaking)
  1003.     {
  1004.       breaking--;
  1005.       break;
  1006.     }
  1007.  
  1008.       if (continuing)
  1009.     {
  1010.       continuing--;
  1011.       if (continuing)
  1012.         break;
  1013.     }
  1014.     }
  1015.   loop_level--;
  1016.  
  1017.   if (commands_executed)
  1018.     return (last_command_exit_value);
  1019.   else
  1020.     return (EXECUTION_SUCCESS);
  1021. }
  1022.  
  1023. /* IF test THEN command [ELSE command].
  1024.    IF also allows ELIF in the place of ELSE IF, but
  1025.    the parser makes *that* stupidity transparent. */
  1026. execute_if_command (if_command)
  1027.      IF_COM *if_command;
  1028. {
  1029.   int return_value;
  1030.  
  1031.   if_command->test->flags |= CMD_IGNORE_RETURN;
  1032.   return_value = execute_command (if_command->test);
  1033.  
  1034.   if (return_value == EXECUTION_SUCCESS)
  1035.     {
  1036.       QUIT;
  1037.       if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
  1038.       if_command->true_case->flags |= CMD_IGNORE_RETURN;
  1039.       return (execute_command (if_command->true_case));
  1040.     }
  1041.   else
  1042.     {
  1043.       QUIT;
  1044.  
  1045.       if (if_command->false_case &&
  1046.       (if_command->flags & CMD_IGNORE_RETURN))
  1047.     {
  1048.       if_command->false_case->flags |= CMD_IGNORE_RETURN;
  1049.     }
  1050.  
  1051.       return (execute_command (if_command->false_case));
  1052.     }
  1053. }
  1054.  
  1055. /* The name of the command that is currently being executed.
  1056.    `test' needs this, for example. */
  1057. char *this_command_name;
  1058.  
  1059. static void
  1060. bind_lastarg (arg)
  1061.      char *arg;
  1062. {
  1063.   SHELL_VAR *var;
  1064.  
  1065.   if (!arg)
  1066.     arg = "";
  1067.   var = bind_variable ("_", arg);
  1068.   var->attributes &= ~att_exported;
  1069. }
  1070.  
  1071. /* For catching RETURN in a function. */
  1072. int return_catch_flag = 0;
  1073. int return_catch_value;
  1074. jmp_buf return_catch;
  1075.  
  1076. /* The meaty part of all the executions.  We have to start hacking the
  1077.    real execution of commands here.  Fork a process, set things up,
  1078.    execute the command. */
  1079. execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
  1080.      SIMPLE_COM *simple_command;
  1081.      int pipe_in, pipe_out;
  1082.      struct fd_bitmap *fds_to_close;
  1083. {
  1084.   extern int command_string_index, variable_context, line_number;
  1085.   extern char *the_printed_command;
  1086.   WORD_LIST *expand_words (), *copy_word_list ();
  1087.   WORD_LIST *words, *lastword;
  1088.   char *command_line, *lastarg;
  1089.   int first_word_quoted, result;
  1090.  
  1091.   result = EXECUTION_SUCCESS;
  1092.  
  1093.   /* If we're in a function, update the pseudo-line-number information. */
  1094.   if (variable_context)
  1095.     line_number++;
  1096.  
  1097.   /* Remember what this command line looks like at invocation. */
  1098.   command_string_index = 0;
  1099.   print_simple_command (simple_command);
  1100.   command_line = (char *)alloca (1 + strlen (the_printed_command));
  1101.   strcpy (command_line, the_printed_command);
  1102.  
  1103.   first_word_quoted =
  1104.     simple_command->words ? simple_command->words->word->quoted : 0;
  1105.  
  1106.   /* If we are re-running this as the result of executing the `command'
  1107.      builtin, do not expand the command words a second time. */
  1108.   if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
  1109.     words = expand_words (simple_command->words);
  1110.   else
  1111.     words = copy_word_list (simple_command->words);
  1112.  
  1113.   lastarg = (char *)NULL;
  1114.   begin_unwind_frame ("simple-command");
  1115.  
  1116.   /* It is possible for WORDS not to have anything left in it.
  1117.      Perhaps all the words consisted of `$foo', and there was
  1118.      no variable `$foo'. */
  1119.   if (words)
  1120.     {
  1121.       extern int dispose_words ();
  1122.       extern Function *last_shell_builtin, *this_shell_builtin;
  1123.       Function *builtin;
  1124.       SHELL_VAR *func;
  1125.       char *auto_resume_value;
  1126.  
  1127.       if (echo_command_at_execute)
  1128.     {
  1129.       extern char *indirection_level_string ();
  1130.       char *line = string_list (words);
  1131.  
  1132.       if (line && *line)
  1133.         fprintf (stderr, "%s%s\n", indirection_level_string (), line);
  1134.  
  1135.       if (line)
  1136.         free (line);
  1137.     }
  1138.  
  1139.       if (simple_command->flags & CMD_NO_FUNCTIONS)
  1140.     func = (SHELL_VAR *)NULL;
  1141.       else
  1142.     func = find_function (words->word->word);
  1143.  
  1144.       add_unwind_protect (dispose_words, words);
  1145.  
  1146.       QUIT;
  1147.  
  1148.       /* Bind the last word in this command to "$_" after execution. */
  1149.       for (lastword = words; lastword->next; lastword = lastword->next);
  1150.       lastarg = lastword->word->word;
  1151.  
  1152. #if defined (JOB_CONTROL)
  1153.       /* Is this command a job control related thing? */
  1154.       if (words->word->word[0] == '%')
  1155.     {
  1156.       int result;
  1157.  
  1158.       if (async)
  1159.         {
  1160.           extern int bg_builtin ();
  1161.  
  1162.           this_command_name = "bg";
  1163.           last_shell_builtin = this_shell_builtin;
  1164.           this_shell_builtin = find_shell_builtin ("bg");
  1165.           result = bg_builtin (words);
  1166.         }
  1167.       else
  1168.         {
  1169.           extern int fg_builtin ();
  1170.  
  1171.           this_command_name = "fg";
  1172.           last_shell_builtin = this_shell_builtin;
  1173.           this_shell_builtin = find_shell_builtin ("fg");
  1174.           result = fg_builtin (words);
  1175.         }
  1176.       goto return_result;
  1177.     }
  1178.  
  1179.       /* One other possiblilty.  The user may want to resume an existing job.
  1180.      If they do, find out whether this word is a candidate for a running
  1181.      job. */
  1182.       if ((auto_resume_value = get_string_value ("auto_resume")) &&
  1183.       !first_word_quoted &&
  1184.       !words->next &&
  1185.       words->word->word[0] &&
  1186.       !simple_command->redirects &&
  1187.       pipe_in == NO_PIPE &&
  1188.       pipe_out == NO_PIPE &&
  1189.       !async)
  1190.     {
  1191.       char *word = words->word->word;
  1192.       register int i, wl = strlen (word), exact;
  1193.  
  1194.       exact = strcmp (auto_resume_value, "exact") == 0;
  1195.       for (i = job_slots - 1; i > -1; i--)
  1196.         {
  1197.           if (jobs[i])
  1198.         {
  1199.           register PROCESS *p = jobs[i]->pipe;
  1200.           do
  1201.             {
  1202.               if ((JOBSTATE (i) == JSTOPPED) &&
  1203.               (strncmp (p->command, word,
  1204.                     exact ? strlen (p->command) : wl) == 0))
  1205.             {
  1206.               int started_status;
  1207.  
  1208.               run_unwind_frame ("simple-command");
  1209.               last_shell_builtin = this_shell_builtin;
  1210.               this_shell_builtin = find_shell_builtin ("fg");
  1211.  
  1212.               started_status = start_job (i, 1);
  1213.  
  1214.               if (started_status < 0)
  1215.                 return (EXECUTION_FAILURE);
  1216.               else
  1217.                 return (started_status);
  1218.             }
  1219.               p = p->next;
  1220.             }
  1221.           while (p != jobs[i]->pipe);
  1222.         }
  1223.         }
  1224.     }
  1225. #endif /* JOB_CONTROL */
  1226.  
  1227.       /* Remember the name of this command globally. */
  1228.       this_command_name = words->word->word;
  1229.  
  1230.       QUIT;
  1231.  
  1232.       /* Not a running job.  Do normal command processing. */
  1233.       maybe_make_export_env ();
  1234.  
  1235.       /* This command could be a shell builtin or a user-defined function.
  1236.      If so, and we have pipes, then fork a subshell in here.  Else, just
  1237.      do the command. */
  1238.  
  1239.       if (func)
  1240.     builtin = (Function *)NULL;
  1241.       else
  1242.     builtin = find_shell_builtin (this_command_name);
  1243.  
  1244.       last_shell_builtin = this_shell_builtin;
  1245.       this_shell_builtin = builtin;
  1246.  
  1247.       if (builtin || func)
  1248.     {
  1249.       put_command_name_into_env (this_command_name);
  1250.       if ((pipe_in != NO_PIPE) || (pipe_out != NO_PIPE) || async)
  1251.         {
  1252.           if (make_child (savestring (command_line), async) == 0)
  1253.         {
  1254.           execute_subshell_builtin_or_function
  1255.             (words, simple_command->redirects, builtin, func,
  1256.              pipe_in, pipe_out, async, fds_to_close,
  1257.              simple_command->flags);
  1258.         }
  1259.           else
  1260.         {
  1261.           close_pipes (pipe_in, pipe_out);
  1262.           goto return_result;
  1263.         }
  1264.         }
  1265.       else
  1266.         {
  1267.           result = execute_builtin_or_function
  1268.         (words, builtin, func, simple_command->redirects, fds_to_close,
  1269.          simple_command->flags);
  1270.  
  1271.           goto return_result;
  1272.         }
  1273.     }
  1274.  
  1275.       execute_disk_command (words, simple_command->redirects, command_line,
  1276.                 pipe_in, pipe_out, async, fds_to_close);
  1277.  
  1278.       goto return_result;
  1279.     }
  1280.   else if (pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
  1281.     {
  1282.       /* We have a null command, but we really want a subshell to take
  1283.      care of it.  Just fork, do piping and redirections, and exit. */
  1284.       if (make_child (savestring (""), async) == 0)
  1285.     {
  1286.       do_piping (pipe_in, pipe_out);
  1287.  
  1288.       if (do_redirections (simple_command->redirects, 1, 0, 0) == 0)
  1289.         exit (EXECUTION_SUCCESS);
  1290.       else
  1291.         exit (EXECUTION_FAILURE);
  1292.     }
  1293.       else
  1294.     {
  1295.       close_pipes (pipe_in, pipe_out);
  1296.       result = EXECUTION_SUCCESS;
  1297.       goto return_result;
  1298.     }
  1299.     }
  1300.   else
  1301.     {
  1302.       result = EXECUTION_FAILURE;
  1303.       /* Even if there aren't any command names, pretend to do the
  1304.      redirections that are specified.  The user expects the side
  1305.      effects to take place. */
  1306.       if (do_redirections (simple_command->redirects, 0, 0, 0) == 0)
  1307.     result = last_command_exit_value;
  1308.     }
  1309.  return_result:
  1310.   bind_lastarg (lastarg);
  1311.   run_unwind_frame ("simple-command");
  1312.   return (result);
  1313. }
  1314.  
  1315. /* Execute a shell builtin or function in a subshell environment.  This
  1316.    routine does not return; it only calls exit().  If BUILTIN is non-null,
  1317.    it points to a function to call to execute a shell builtin; otherwise
  1318.    VAR points at the body of a function to execute.  WORDS is the arguments
  1319.    to the command, REDIRECTS specifies redirections to perform before the
  1320.    command is executed. */
  1321. static void
  1322. execute_subshell_builtin_or_function (words, redirects, builtin, var,
  1323.                       pipe_in, pipe_out, async, fds_to_close,
  1324.                       flags)
  1325.      WORD_LIST *words;
  1326.      REDIRECT *redirects;
  1327.      Function *builtin;
  1328.      SHELL_VAR *var;
  1329.      int pipe_in, pipe_out, async;
  1330.      struct fd_bitmap *fds_to_close;
  1331.      int flags;
  1332. {
  1333.   extern int login_shell, interactive;
  1334.   extern int jobs_builtin ();
  1335.  
  1336.   /* A subshell is neither a login shell nor interactive. */
  1337.   login_shell = interactive = 0;
  1338.  
  1339. #if defined (JOB_CONTROL)
  1340.   /* Eradicate all traces of job control after we fork the subshell, so
  1341.      all jobs begun by this subshell are in the same process group as
  1342.      the shell itself. */
  1343.  
  1344.   /* Allow the output of `jobs' to be piped. */
  1345.   if (builtin == jobs_builtin && !async &&
  1346.       pipe_out != NO_PIPE && pipe_in != NO_PIPE)
  1347.     kill_current_pipeline ();
  1348.   else
  1349.     without_job_control ();
  1350. #endif /* JOB_CONTROL */
  1351.  
  1352.   do_piping (pipe_in, pipe_out);
  1353.  
  1354.   if (fds_to_close)
  1355.     close_fd_bitmap (fds_to_close);
  1356.  
  1357.   if (do_redirections (redirects, 1, 0, 0) != 0)
  1358.     exit (EXECUTION_FAILURE);
  1359.  
  1360.   if (builtin)
  1361.     {
  1362.       int result;
  1363.       extern jmp_buf top_level;
  1364.  
  1365.       /* Save the values of pipe_in and pipe_out for
  1366.      possible later use by parse_and_execute (). */
  1367.       builtin_pipe_in = pipe_in;
  1368.       builtin_pipe_out = pipe_out;
  1369.  
  1370.       /* Give builtins a place to jump back to on failure,
  1371.      so we don't go back up to main(). */
  1372.       if (result = setjmp (top_level))
  1373.     exit (result);  
  1374.       exit ((*builtin) (words->next));
  1375.     }
  1376.   else
  1377.     {
  1378.       COMMAND *fc, *tc = (COMMAND *)function_cell (var);
  1379.       int result;
  1380.       extern int variable_context, line_number;
  1381.  
  1382.       remember_args (words->next, 1);
  1383.       line_number = 0;
  1384. #ifdef JOB_CONTROL
  1385.       stop_pipeline (async, (COMMAND *)NULL);
  1386. #endif
  1387.       variable_context++;
  1388.       return_catch_flag++;
  1389.  
  1390.       /* We can do this because function bodies are always guaranteed to
  1391.      be group commands, according to the grammar in parse.y.  If we
  1392.      don't do this now, execute_command_internal will graciously fork
  1393.      another subshell for us, and we'll lose contact with the rest of
  1394.      the pipeline and fail to get any SIGPIPE that might be sent. */
  1395.  
  1396.       if (tc->type == cm_group)
  1397.     fc = (COMMAND *)copy_command (tc->value.Group->command);
  1398.       else
  1399.     fc = (COMMAND *)copy_command (tc);
  1400.  
  1401.       if (fc && (flags & CMD_IGNORE_RETURN))
  1402.     fc->flags |= CMD_IGNORE_RETURN;
  1403.  
  1404.       /* result = execute_command (fc); doesn't work.
  1405.      We need to explicitly specify the pipes in and out so that they
  1406.      are closed in all the processes that rely on their being closed.
  1407.      If they are not, it is possible to not get the SIGPIPE that we
  1408.      need to kill all the processes sharing the pipe. */
  1409.  
  1410.       result = execute_command_internal (fc, 0, pipe_in, pipe_out,
  1411.                      fds_to_close);
  1412.  
  1413.       dispose_command (fc);
  1414.       variable_context--;
  1415.  
  1416.       exit (result);
  1417.     }
  1418. }
  1419.  
  1420. /* Execute a builtin or function in the current shell context.  If BUILTIN
  1421.    is non-null, it is the builtin command to execute, otherwise VAR points
  1422.    to the body of a function.  WORDS are the command's arguments, REDIRECTS
  1423.    are the redirections to perform.  FDS_TO_CLOSE is the usual bitmap of
  1424.    file descriptors to close.
  1425.  
  1426.    If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
  1427.    not undone before this function returns. */
  1428. static int
  1429. execute_builtin_or_function (words, builtin, var, redirects,
  1430.                  fds_to_close, flags)
  1431.      WORD_LIST *words;
  1432.      Function *builtin;
  1433.      SHELL_VAR *var;
  1434.      REDIRECT *redirects;
  1435.      struct fd_bitmap *fds_to_close;
  1436.      int flags;
  1437. {
  1438.   extern int exec_builtin (), eval_builtin ();
  1439.   int result = EXECUTION_FAILURE;
  1440.   int redir_result;
  1441.   REDIRECT *saved_undo_list;
  1442.  
  1443.   redir_result = do_redirections (redirects, 1, 1, 0);
  1444.  
  1445.   if (redir_result != 0)
  1446.     return (EXECUTION_FAILURE);
  1447.  
  1448.   saved_undo_list = redirection_undo_list;
  1449.  
  1450.   /* Calling the "exec" builtin changes redirections forever. */
  1451.   if (builtin == exec_builtin)
  1452.     {
  1453.       dispose_redirects (saved_undo_list);
  1454.       saved_undo_list = (REDIRECT *)NULL;
  1455.     }
  1456.   else
  1457.     {
  1458.       begin_unwind_frame ("saved redirects");
  1459.       add_unwind_protect (cleanup_func_redirects, (char *)saved_undo_list);
  1460.     }
  1461.  
  1462.   redirection_undo_list = (REDIRECT *)NULL;
  1463.  
  1464.   if (builtin)
  1465.     {
  1466.       int old_e_flag = exit_immediately_on_error;
  1467.  
  1468.       /* The eval builtin calls parse_and_execute, which does not know about
  1469.      the setting of flags, and always calls the execution functions with
  1470.      flags that will exit the shell on an error if -e is set.  If the
  1471.      eval builtin is being called, and we're supposed to ignore the exit
  1472.      value of the command, we turn the -e flag off ourselves, then
  1473.      restore it when the command completes. */
  1474.       if ((builtin == eval_builtin) && (flags & CMD_IGNORE_RETURN))
  1475.     {
  1476.       begin_unwind_frame ("eval_builtin");
  1477.       unwind_protect_int (exit_immediately_on_error);
  1478.       exit_immediately_on_error = 0;
  1479.     }
  1480.  
  1481.       result = ((*builtin) (words->next));
  1482.  
  1483.       if ((builtin == eval_builtin) && (flags & CMD_IGNORE_RETURN))
  1484.     {
  1485.       exit_immediately_on_error += old_e_flag;
  1486.       discard_unwind_frame ("eval_builtin");
  1487.     }
  1488.     }
  1489.   else
  1490.     {
  1491.       int return_val;
  1492.       extern int dispose_command (), pop_context ();
  1493.       jmp_buf old_return_catch;
  1494.       COMMAND *tc;
  1495.       extern int line_number;
  1496.  
  1497.       tc = (COMMAND *)copy_command (function_cell (var));
  1498.       if (tc && (flags & CMD_IGNORE_RETURN))
  1499.     tc->flags |= CMD_IGNORE_RETURN;
  1500.  
  1501.       push_context ();
  1502.       begin_unwind_frame ("function_calling");
  1503.       add_unwind_protect (pop_context, (char *)NULL);
  1504.       add_unwind_protect (dispose_command, (char *)tc);
  1505.  
  1506.       /* Note the second argument of "1", meaning that
  1507.      we discard the current value of "$*"!  This
  1508.      is apparently the right thing. */
  1509.       remember_args (words->next, 1);
  1510.  
  1511.       line_number = 0;
  1512.       return_catch_flag++;
  1513.       bcopy ((char *)return_catch, (char *)old_return_catch, sizeof (jmp_buf));
  1514.       return_val =  setjmp (return_catch);
  1515.  
  1516.       if (return_val)
  1517.     result = return_catch_value;
  1518.       else
  1519.     result = execute_command_internal (tc, 0, NO_PIPE, NO_PIPE,
  1520.                        fds_to_close);
  1521.  
  1522.       run_unwind_frame ("function_calling");
  1523.       return_catch_flag--;
  1524.       bcopy ((char *)old_return_catch, (char *)return_catch, sizeof (jmp_buf));
  1525.     }
  1526.  
  1527.   redirection_undo_list = saved_undo_list;
  1528.   if (builtin != exec_builtin)
  1529.     discard_unwind_frame ("saved redirects");
  1530.   do_redirections (redirection_undo_list, 1, 0, 0);
  1531.  
  1532.   return (result);
  1533. }
  1534.  
  1535. /* Execute a simple command that is hopefully defined in a disk file
  1536.    somewhere.
  1537.  
  1538.    1) fork ()
  1539.    2) connect pipes
  1540.    3) look up the command
  1541.    4) do redirections
  1542.    5) execve ()
  1543.    6) If the execve failed, see if the file has executable mode set.
  1544.    If so, and it isn't a directory, then execute its contents as
  1545.    a shell script.
  1546.  
  1547.    Note that the filename hashing stuff has to take place up here,
  1548.    in the parent.  This is probably why the Bourne style shells
  1549.    don't handle it, since that would require them to go through
  1550.    this gnarly hair, for no good reason.  */
  1551. static void
  1552. execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
  1553.               async, fds_to_close)
  1554.      WORD_LIST *words;
  1555.      REDIRECT *redirects;
  1556.      char *command_line;
  1557.      int pipe_in, pipe_out, async;
  1558.      struct fd_bitmap *fds_to_close;
  1559. {
  1560.   char **make_word_array (), *find_user_command (),
  1561.   *find_hashed_filename ();
  1562.  
  1563.   char *hashed_file = (char *)NULL, *command, **args;
  1564.  
  1565.   /* Don't waste time trying to find hashed data for a pathname
  1566.      that is already completely specified. */
  1567.  
  1568.   if (!absolute_program (words->word->word))
  1569.     hashed_file = find_hashed_filename (words->word->word);
  1570.  
  1571.   if (hashed_file)
  1572.     command = savestring (hashed_file);
  1573.   else
  1574.     {
  1575.       /* A command containing a slash is not looked up in PATH. */
  1576.       if (absolute_program (words->word->word))
  1577.     command = savestring (words->word->word);
  1578.       else
  1579.     command = find_user_command (words->word->word);
  1580.  
  1581.       if (command && !hashing_disabled)
  1582.     {
  1583.       extern int dot_found_in_search;
  1584.       /* A command name containing a slash is not saved in the
  1585.          hash table. */
  1586.       if (!absolute_program (words->word->word))
  1587.         remember_filename (words->word->word, command, dot_found_in_search);
  1588.       /* Increase the number of hits to 1. */
  1589.       find_hashed_filename (words->word->word);
  1590.     }
  1591.     }
  1592.  
  1593.   if (command)
  1594.     {
  1595.       put_command_name_into_env (command);
  1596.     }
  1597.  
  1598.   /* We have to make the child before we check for the non-existance
  1599.      of COMMAND, since we want the error messages to be redirected. */
  1600.  
  1601.   if (make_child (savestring (command_line), async) == 0)
  1602.     {
  1603.       do_piping (pipe_in, pipe_out);
  1604.  
  1605.       /* Execve expects the command name to be in args[0].  So we
  1606.      leave it there, in the same format that the user used to
  1607.      type it in. */
  1608.       args = make_word_array (words);
  1609.  
  1610.       if (!command)
  1611.     {
  1612.       report_error ("%s: command not found", args[0]);
  1613.       exit (EXECUTION_FAILURE);
  1614.     }
  1615.  
  1616.       /* This functionality is now provided by close-on-exec of the
  1617.      file descriptors manipulated by redirection and piping.
  1618.      Some file descriptors still need to be closed in all children
  1619.      because of the way bash does pipes; fds_to_close is a 
  1620.      bitmap of all such file descriptors. */
  1621.       if (fds_to_close)
  1622.     close_fd_bitmap (fds_to_close);
  1623.  
  1624.       if (do_redirections (redirects, 1, 0, 0) == 0)
  1625.     {
  1626.       signal (SIGCHLD, SIG_DFL);
  1627.       exit (shell_execve (command, args, export_env));
  1628.     }
  1629.       else
  1630.     exit (EXECUTION_FAILURE);
  1631.     }
  1632.   else
  1633.     {
  1634.       /* Make sure that the pipes are closed in the parent. */
  1635.       close_pipes (pipe_in, pipe_out);
  1636.       free (command);
  1637.     }
  1638. }
  1639.  
  1640. /* If the operating system on which we're running does not handle
  1641.    the #! executable format, then help out.  SAMPLE is the text read
  1642.    from the file, SAMPLE_LEN characters.  COMMAND is the name of
  1643.    the script; it and ARGS, the arguments given by the user, will
  1644.    become arguments to the specified interpreter.  ENV is the environment
  1645.    to pass to the interpreter.
  1646.  
  1647.    The word immediately following the #! is the interpreter to execute.
  1648.    A single argument to the interpreter is allowed. */
  1649. static int
  1650. execute_shell_script (sample, sample_len, command, args, env)
  1651.      unsigned char *sample;
  1652.      int sample_len;
  1653.      char *command;
  1654.      char **args, **env;
  1655. {
  1656.   extern char *shell_name;
  1657.   register int i;
  1658.   char *execname, *firstarg;
  1659.   int start, size_increment, larry;
  1660.  
  1661.   /* Find the name of the interpreter to exec. */
  1662.   for (i = 2; whitespace (sample[i]) && i < sample_len; i++)
  1663.     ;
  1664.  
  1665.   for (start = i;
  1666.        !whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
  1667.        i++)
  1668.     ;
  1669.  
  1670.   execname = (char *)xmalloc (1 + (i - start));
  1671.   strncpy (execname, sample + start, i - start);
  1672.   execname[i - start] = '\0';
  1673.   size_increment = 1;
  1674.  
  1675.   /* Now the argument, if any. */
  1676.   firstarg = (char *)NULL;
  1677.   for (start = i;
  1678.        whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
  1679.        i++)
  1680.     ;
  1681.  
  1682.   /* If there is more text on the line, then it is an argument for the
  1683.      interpreter. */
  1684.   if (i < sample_len && sample[i] != '\n' && !whitespace (sample[i]))
  1685.     {
  1686.       for (start = i;
  1687.        !whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
  1688.        i++)
  1689.     ;
  1690.       firstarg = (char *)xmalloc (1 + (i - start));
  1691.       strncpy (firstarg, sample + start, i - start);
  1692.       firstarg[i - start] = '\0';
  1693.  
  1694.       size_increment = 2;
  1695.     }
  1696.  
  1697.   larry = array_len (args) + size_increment;
  1698.  
  1699.   args = (char **)xrealloc (args, (1 + larry) * sizeof (char *));
  1700.  
  1701.   for (i = larry - 1; i; i--)
  1702.     args[i] = args[i - size_increment];
  1703.  
  1704.   args[0] = execname;
  1705.   if (firstarg)
  1706.     {
  1707.       args[1] = firstarg;
  1708.       args[2] = command;
  1709.     }
  1710.   else
  1711.     args[1] = command;
  1712.  
  1713.   args[larry] = (char *)NULL;
  1714.  
  1715.   return (shell_execve (execname, args, env));
  1716. }
  1717.  
  1718. /* Call execve (), handling interpreting shell scripts, and handling
  1719.    exec failures. */
  1720. int
  1721. shell_execve (command, args, env)
  1722.      char *command;
  1723.      char **args, **env;
  1724. {
  1725. #if defined (isc386) && defined (__STDC__)
  1726.   __setostype (0);        /* Turn on USGr3 semantics. */
  1727.   execve (command, args, env);
  1728.   __setostype (1);        /* Turn the POSIX semantics back on. */
  1729. #else
  1730.   execve (command, args, env);
  1731. #endif /* isc386 && __STDC__ */
  1732.  
  1733.   /* If we get to this point, then start checking out the file.
  1734.      Maybe it is something we can hack ourselves. */
  1735.   {
  1736.     struct stat finfo;
  1737.  
  1738.     if (errno != ENOEXEC)
  1739.       {
  1740.     if ((stat (command, &finfo) == 0) &&
  1741.         (S_ISDIR (finfo.st_mode)))
  1742.       report_error ("%s: is a directory", args[0]);
  1743.     else
  1744.       file_error (command);
  1745.  
  1746.     return (EXECUTION_FAILURE);
  1747.       }
  1748.     else
  1749.       {
  1750.     /* This file is executable.
  1751.        If it begins with #!, then help out people with losing operating
  1752.        systems.  Otherwise, check to see if it is a binary file by seeing
  1753.        if the first line (or up to 30 characters) are in the ASCII set.
  1754.        Execute the contents as shell commands. */
  1755.     extern char *shell_name;
  1756.     int larray = array_len (args) + 1;
  1757.     int i, should_exec = 0;
  1758.  
  1759.     {
  1760.       int fd = open (command, O_RDONLY);
  1761.       if (fd != -1)
  1762.         {
  1763.           unsigned char sample[80];
  1764.           int sample_len = read (fd, &sample[0], 80);
  1765.  
  1766.           /* Is this supposed to be an executable script? */
  1767.           /* If so, the format of the line is "#! interpreter [argument]".
  1768.          A single argument is allowed.  The BSD kernel restricts
  1769.          the length of the entire line to 32 characters (32 bytes
  1770.          being the size of the BSD exec header), but we allow 80
  1771.          characters. */
  1772.  
  1773.           if (sample[0] == '#' && sample[1] == '!')
  1774.         {
  1775.           close (fd);
  1776.           return (execute_shell_script (sample, sample_len,
  1777.                           command, args, env));
  1778.         }
  1779. #if defined (NOTDEF)
  1780. #if defined (HAVE_CSH) && ( defined (Bsd) || defined (Ultrix) )
  1781.           /* If this system has Csh, then keep the old
  1782.          BSD semantics. */
  1783.           else if (sample_len > 0 && sample[0] == '#')
  1784.         {
  1785.           /* Scripts starting with a # are for Csh. */
  1786.           shell_name = savestring ("/bin/csh");
  1787.           should_exec = 1;
  1788.         }
  1789. #endif /* HAVE_CSH */
  1790. #endif /* NOTDEF */
  1791.           else
  1792.         {
  1793.           if (sample_len != -1)
  1794.             if (check_binary_file (sample, sample_len))
  1795.               {
  1796.             report_error ("%s: cannot execute binary file",
  1797.                       command);
  1798.             return (EX_BINARY_FILE);
  1799.               }
  1800.         }
  1801.           close (fd);
  1802.         }
  1803.     }
  1804. #if defined (JOB_CONTROL)
  1805.     /* Forget about the way that job control was working. We are
  1806.        in a subshell. */
  1807.     without_job_control ();
  1808. #endif /* JOB_CONTROL */
  1809. #if defined (ALIAS)
  1810.     /* Forget about any aliases that we knew of.  We are in a subshell. */
  1811.     delete_all_aliases ();
  1812. #endif /* ALIAS */
  1813.     /* Insert the name of this shell into the argument list. */
  1814.     args = (char **)xrealloc (args, (1 + larray) * sizeof (char *));
  1815.  
  1816.     for (i = larray - 1; i; i--)
  1817.       args[i] = args[i - 1];
  1818.  
  1819.     args[0] = shell_name;
  1820.     args[1] = command;
  1821.     args[larray] = (char *)NULL;
  1822.  
  1823.     if (args[0][0] == '-')
  1824.       args[0]++;
  1825.  
  1826.     if (should_exec)
  1827.       {
  1828.         struct stat finfo;
  1829.  
  1830. #if defined (isc386) && defined (__STDC__)
  1831.         __setostype (0);    /* Turn on USGr3 semantics. */
  1832.         execve (shell_name, args, env);
  1833.         __setostype (1);    /* Turn the POSIX semantics back on. */
  1834. #else
  1835.         execve (shell_name, args, env);
  1836. #endif /* isc386 && __STDC__ */
  1837.  
  1838.         /* Oh, no!  We couldn't even exec this! */
  1839.         if ((stat (args[0], &finfo) == 0) && (S_ISDIR (finfo.st_mode)))
  1840.           report_error ("%s: is a directory", args[0]);
  1841.         else
  1842.           file_error (args[0]);
  1843.  
  1844.         return (EXECUTION_FAILURE);
  1845.       }
  1846.     else
  1847.       {
  1848.         extern jmp_buf subshell_top_level;
  1849.         extern int subshell_argc;
  1850.         extern char **subshell_argv;
  1851.         extern char **subshell_envp;
  1852.  
  1853.         subshell_argc = larray;
  1854.         subshell_argv = args;
  1855.         subshell_envp = env;
  1856.         longjmp (subshell_top_level, 1);
  1857.       }
  1858.       }
  1859.   }
  1860. }
  1861.  
  1862. static void
  1863. close_all_files ()
  1864. {
  1865.   register int i, fd_table_size;
  1866.  
  1867.   fd_table_size = getdtablesize ();
  1868.  
  1869.   for (i = 3; i < fd_table_size; i++)
  1870.     close (i);
  1871. }
  1872.  
  1873. static void
  1874. close_pipes (in, out)
  1875.      int in, out;
  1876. {
  1877.   if (in >= 0) close (in);
  1878.   if (out >= 0) close (out);
  1879. }
  1880.  
  1881. /* Redirect input and output to be from and to the specified pipes.
  1882.    NO_PIPE and REDIRECT_BOTH are handled correctly. */
  1883. static void
  1884. do_piping (pipe_in, pipe_out)
  1885.      int pipe_in, pipe_out;
  1886. {
  1887.   if (pipe_in != NO_PIPE)
  1888.     {
  1889.       dup2 (pipe_in, 0);
  1890.       close (pipe_in);
  1891.     }
  1892.   if (pipe_out != NO_PIPE)
  1893.     {
  1894.       dup2 (pipe_out, 1);
  1895.       close (pipe_out);
  1896.  
  1897.       if (pipe_out == REDIRECT_BOTH)
  1898.     dup2 (1, 2);
  1899.     }
  1900. }
  1901.  
  1902. /* Defined in flags.c.  Non-zero means don't overwrite existing files. */
  1903. extern int noclobber;
  1904.  
  1905. #define AMBIGUOUS_REDIRECT -1
  1906. #define NOCLOBBER_REDIRECT -2
  1907. /* Perform the redirections on LIST.  If FOR_REAL, then actually make
  1908.    input and output file descriptors, otherwise just do whatever is
  1909.    neccessary for side effecting.  INTERNAL says to remember how to
  1910.    undo the redirections later, if non-zero.  If SET_CLEXEC is non-zero,
  1911.    file descriptors opened in do_redirection () have their close-on-exec
  1912.    flag set. */
  1913. static int
  1914. do_redirections (list, for_real, internal, set_clexec)
  1915.      REDIRECT *list;
  1916.      int for_real, internal;
  1917. {
  1918.   register int error;
  1919.   register REDIRECT *temp = list;
  1920.  
  1921.   if (internal && redirection_undo_list)
  1922.     {
  1923.       dispose_redirects (redirection_undo_list);
  1924.       redirection_undo_list = (REDIRECT *)NULL;
  1925.     }
  1926.  
  1927.   while (temp)
  1928.     {
  1929.       extern char *strerror ();
  1930.  
  1931.       error = do_redirection_internal (temp, for_real, internal, set_clexec);
  1932.  
  1933.       if (error)
  1934.     {
  1935.       char *redirection_expand (), *itos ();
  1936.       char *filename;
  1937.  
  1938.       if (expandable_redirection_filename (temp))
  1939.         {
  1940.           filename = redirection_expand (temp->redirectee.filename);
  1941.           if (!filename)
  1942.         filename = savestring ("");
  1943.         }
  1944.       else
  1945.         filename = itos (temp->redirectee.dest);
  1946.  
  1947.       switch (error)
  1948.         {
  1949.         case AMBIGUOUS_REDIRECT:
  1950.           report_error ("%s: Ambiguous redirect", filename);
  1951.           break;
  1952.  
  1953.         case NOCLOBBER_REDIRECT:
  1954.           report_error ("%s: Cannot clobber existing file", filename);
  1955.           break;
  1956.  
  1957.         default:
  1958.           report_error ("%s: %s", filename, strerror (error));
  1959.           break;
  1960.         }
  1961.  
  1962.       free (filename);
  1963.       return (error);
  1964.     }
  1965.  
  1966.       temp = temp->next;
  1967.     }
  1968.   return (0);
  1969. }
  1970.  
  1971. /* Return non-zero if the redirection pointed to by REDIRECT has a
  1972.    redirectee.filename that can be expanded. */
  1973. static int
  1974. expandable_redirection_filename (redirect)
  1975.      REDIRECT *redirect;
  1976. {
  1977.   int result;
  1978.  
  1979.   switch (redirect->instruction)
  1980.     {
  1981.     case r_output_direction:
  1982.     case r_appending_to:
  1983.     case r_input_direction:
  1984.     case r_inputa_direction:
  1985.     case r_err_and_out:
  1986.     case r_input_output:
  1987.     case r_output_force:
  1988.       result = 1;
  1989.       break;
  1990.  
  1991.     default:
  1992.       result = 0;
  1993.     }
  1994.   return (result);
  1995. }
  1996.  
  1997. /* Expand the word in WORD returning a string.  If WORD expands to
  1998.    multiple words (or no words), then return NULL. */
  1999. char *
  2000. redirection_expand (word)
  2001.      WORD_DESC *word;
  2002. {
  2003.   char *result;
  2004.   WORD_LIST *make_word_list (), *expand_words_no_vars ();
  2005.   WORD_LIST *tlist1, *tlist2;
  2006.  
  2007.   tlist1 = make_word_list (copy_word (word), (WORD_LIST *)NULL);
  2008.   tlist2 = expand_words_no_vars (tlist1);
  2009.   dispose_words (tlist1);
  2010.  
  2011.   if (!tlist2 || tlist2->next)
  2012.     {
  2013.       /* We expanded to no words, or to more than a single word.
  2014.      Dispose of the word list and return NULL. */
  2015.       if (tlist2)
  2016.     dispose_words (tlist2);
  2017.       return ((char *)NULL);
  2018.     }
  2019.   result = string_list (tlist2);
  2020.   dispose_words (tlist2);
  2021.   return (result);
  2022. }
  2023.  
  2024. /* Do the specific redirection requested.  Returns errno in case of error.
  2025.    If FOR_REAL is zero, then just do whatever is neccessary to produce the
  2026.    appropriate side effects.   REMEMBERING, if non-zero, says to remember
  2027.    how to undo each redirection.  If SET_CLEXEC is non-zero, then
  2028.    we set all file descriptors > 2 that we open to be close-on-exec.  */
  2029. static int
  2030. do_redirection_internal (redirect, for_real, remembering, set_clexec)
  2031.      REDIRECT *redirect;
  2032.      int for_real, remembering;
  2033. {
  2034.   WORD_DESC *redirectee = redirect->redirectee.filename;
  2035.   int redirector = redirect->redirector;
  2036.   char *redirectee_word;
  2037.   enum r_instruction ri = redirect->instruction;
  2038.  
  2039.   int fd;
  2040.  
  2041.   switch (ri)
  2042.     {
  2043.     case r_output_direction:
  2044.     case r_appending_to:
  2045.     case r_input_direction:
  2046.     case r_inputa_direction:
  2047.     case r_err_and_out:        /* command &>filename */
  2048.     case r_input_output:
  2049.     case r_output_force:
  2050.  
  2051.       if (!(redirectee_word = redirection_expand (redirectee)))
  2052.     return (AMBIGUOUS_REDIRECT);
  2053.  
  2054.       /* If we are in noclobber mode, you are not allowed to overwrite
  2055.        existing files.  Check first. */
  2056.       if (noclobber && (ri == r_output_direction ||
  2057.               ri == r_input_output ||
  2058.               ri == r_err_and_out))
  2059.       {
  2060.     struct stat buf;
  2061.     if ((stat (redirectee_word, &buf) == 0) &&
  2062.         (S_ISREG (buf.st_mode)))
  2063.       return (NOCLOBBER_REDIRECT);
  2064.       }
  2065.  
  2066.       fd = open (redirectee_word, redirect->flags, 0666);
  2067.       free (redirectee_word);
  2068.  
  2069.       if (fd < 0 )
  2070.     return (errno);
  2071.  
  2072.       if (for_real)
  2073.     {
  2074.       if (remembering)
  2075.         /* Only setup to undo it if the thing to undo is active. */
  2076.         if ((fd != redirector) && (fcntl (redirector, F_GETFD, 0) != -1))
  2077.           add_undo_redirect (redirector);
  2078.         else
  2079.           add_undo_close_redirect (redirector);
  2080.  
  2081.       if ((fd != redirector) && (dup2 (fd, redirector) < 0))
  2082.         return (errno);
  2083.  
  2084.       /*
  2085.        * If we're remembering, then this is the result of a while, for
  2086.        * or until loop with a loop redirection, or a function/builtin
  2087.        * executing in the parent shell with a redirection.  In the
  2088.        * function/builtin case, we want to set all file descriptors > 2
  2089.        * to be close-on-exec to duplicate the effect of the old
  2090.        * for i = 3 to NOFILE close(i) loop.  In the case of the loops,
  2091.        * both sh and ksh leave the file descriptors open across execs.
  2092.        * The Posix standard mentions only the exec builtin.
  2093.        */
  2094.       if (set_clexec && (redirector > 2))
  2095.         SET_CLOSE_ON_EXEC (redirector);
  2096.     }
  2097.       if (fd != redirector)
  2098.     close (fd);        /* Don't close what we just opened! */
  2099.  
  2100.       /* If we are hacking both stdout and stderr, do the stderr
  2101.      redirection here. */
  2102.       if (redirect->instruction == r_err_and_out)
  2103.     {
  2104.       if (for_real)
  2105.         {
  2106.           if (remembering)
  2107.         add_undo_redirect (2);
  2108.           dup2 (1, 2);
  2109.         }
  2110.     }
  2111.       break;
  2112.  
  2113.     case r_reading_until:
  2114.     case r_deblank_reading_until:
  2115.       {
  2116.     /* REDIRECTEE is a pointer to a WORD_DESC containing the text of
  2117.        the new input.  Place it in a temporary file. */
  2118.     int document_index = 0;
  2119.     char *document = (char *)NULL;
  2120.  
  2121.     /* Expand the text if the word that was specified had no quoting.
  2122.        Note that the text that we expand is treated exactly as if it
  2123.        were surrounded by double-quotes.  */
  2124.  
  2125.     if (!redirectee)
  2126.       document = savestring ("");
  2127.     else
  2128.       {
  2129.         if (!redirectee->quoted)
  2130.           {
  2131.         WORD_LIST *temp_word_list =
  2132.           (WORD_LIST *)expand_string (redirectee->word,
  2133.                           Q_HERE_DOCUMENT);
  2134.  
  2135.         document = string_list (temp_word_list);
  2136.         if (!document)
  2137.           document = savestring ("");
  2138.         dispose_words (temp_word_list);
  2139.           }
  2140.         else
  2141.           {
  2142.         document = redirectee->word;
  2143.           }
  2144.         document_index = strlen (document);
  2145.  
  2146.         {
  2147.           char filename[40];
  2148.           pid_t pid = getpid ();
  2149.  
  2150.           /* Make the filename for the temp file. */
  2151.           sprintf (filename, "/tmp/t%d-sh", pid);
  2152.  
  2153.           fd = open (filename, O_TRUNC | O_WRONLY | O_CREAT, 0666);
  2154.           if (fd < 0)
  2155.         {
  2156.           if (!redirectee->quoted)
  2157.             free (document);
  2158.           return (errno);
  2159.         }
  2160.  
  2161.           write (fd, document, document_index);
  2162.           close (fd);
  2163.  
  2164.           if (!redirectee->quoted)
  2165.         free (document);
  2166.  
  2167.           /* Make the document really temporary.  Also make it the
  2168.          input. */
  2169.           fd = open (filename, O_RDONLY, 0666);
  2170.  
  2171.           if (unlink (filename) < 0 || fd < 0)
  2172.         return (errno);
  2173.  
  2174.           if (for_real)
  2175.         {
  2176.           if (remembering)
  2177.             /* Only setup to undo it if the thing to undo is active. */
  2178.             if ((fd != redirector) &&
  2179.             (fcntl (redirector, F_GETFD, 0) != -1))
  2180.               add_undo_redirect (redirector);
  2181.             else
  2182.               add_undo_close_redirect (redirector);
  2183.  
  2184.           if (dup2 (fd, redirector) < 0)
  2185.             return (errno);
  2186.  
  2187.           if (set_clexec && (redirector > 2))
  2188.             SET_CLOSE_ON_EXEC (redirector);
  2189.         }
  2190.           close (fd);
  2191.         }
  2192.       }
  2193.       }
  2194.       break;
  2195.  
  2196.     case r_duplicating:
  2197.       if (for_real)
  2198.     {
  2199.       if (remembering)
  2200.         /* Only setup to undo it if the thing to undo is active. */
  2201.         if (((int)redirectee != redirector) &&
  2202.         (fcntl (redirector, F_GETFD, 0) != -1))
  2203.           add_undo_redirect (redirector);
  2204.         else
  2205.           add_undo_close_redirect (redirector);
  2206.  
  2207.       /* This is correct.  2>&1 means dup2 (1, 2); */
  2208.       dup2 ((int)redirectee, redirector);
  2209.  
  2210.       /* First duplicate the close-on-exec state of redirectee.  dup2
  2211.          leaves the flag unset on the new descriptor, which means it
  2212.          stays open.  Only set the close-on-exec bit for file descriptors
  2213.          greater than 2 in any case, since 0-2 should always be open
  2214.          unless closed by something like `exec 2<&-'. */
  2215.       /* if ((already_set || set_unconditionally) && (ok_to_set))
  2216.         set_it () */
  2217.       if (((fcntl ((int)redirectee, F_GETFD, 0) == 1) || set_clexec) &&
  2218.            (redirector > 2))
  2219.         SET_CLOSE_ON_EXEC (redirector);
  2220.     }
  2221.       break;
  2222.  
  2223.     case r_close_this:
  2224.       if (for_real)
  2225.     {
  2226.       if (remembering && (fcntl (redirector, F_GETFD, 0) != -1))
  2227.         add_undo_redirect (redirector);
  2228.  
  2229.       close (redirector);
  2230.     }
  2231.       break;
  2232.     }
  2233.   return (0);
  2234. }
  2235.  
  2236. #define SHELL_FD_BASE    10
  2237.  
  2238. /* Remember the file descriptor associated with the slot FD,
  2239.    on REDIRECTION_UNDO_LIST.  Note that the list will be reversed
  2240.    before it is executed. */
  2241. static int
  2242. add_undo_redirect (fd)
  2243.      int fd;
  2244. {
  2245.   int new_fd, clexec_flag;
  2246.   REDIRECT *new_redirect, *closer;
  2247.  
  2248.   new_fd = fcntl (fd, F_DUPFD, SHELL_FD_BASE);
  2249.  
  2250.   if (new_fd < 0)
  2251.     {
  2252.       file_error ("redirection error");
  2253.       return (-1);
  2254.     }
  2255.   else
  2256.     {
  2257.       clexec_flag = fcntl (fd, F_GETFD, 0);
  2258.       closer = make_redirection (new_fd, r_close_this, 0);
  2259.       new_redirect = make_redirection (fd, r_duplicating, new_fd);
  2260.       new_redirect->next = closer;
  2261.       closer->next = redirection_undo_list;
  2262.       redirection_undo_list = new_redirect;
  2263.       /*
  2264.        * File descriptors used only for saving others should always be
  2265.        * marked close-on-exec.  Unfortunately, we have to preserve the
  2266.        * close-on-exec state of the file descriptor we are saving, since
  2267.        * fcntl (F_DUPFD) sets the new file descriptor to remain open
  2268.        * across execs.  If, however, the file descriptor whose state we
  2269.        * are saving is <= 2, we can just set the close-on-exec flag,
  2270.        * because file descriptors 0-2 should always be open-on-exec,
  2271.        * and the restore above in do_redirection() will take care of it.
  2272.        */
  2273.       if (clexec_flag || fd < 3)
  2274.     SET_CLOSE_ON_EXEC (new_fd);
  2275.     }
  2276.   return (0);
  2277. }
  2278.  
  2279. /* Set up to close FD when we are finished with the current command
  2280.    and its redirections. */
  2281. static void
  2282. add_undo_close_redirect (fd)
  2283.      int fd;
  2284. {
  2285.   REDIRECT *closer;
  2286.  
  2287.   closer = make_redirection (fd, r_close_this, 0);
  2288.   closer->next = redirection_undo_list;
  2289.   redirection_undo_list = closer;
  2290. }
  2291.  
  2292. intern_function (name, function)
  2293.      WORD_DESC *name;
  2294.      COMMAND *function;
  2295. {
  2296.   SHELL_VAR *var;
  2297.  
  2298.   if (!check_identifier (name))
  2299.     return (EXECUTION_FAILURE);
  2300.  
  2301.   var = find_function (name->word);
  2302.   if (var && readonly_p (var))
  2303.     {
  2304.       report_error ("%s: readonly function", var->name);
  2305.       return (EXECUTION_FAILURE);
  2306.     }
  2307.  
  2308.   bind_function (name->word, function);
  2309.   return (EXECUTION_SUCCESS);
  2310. }
  2311.  
  2312. /* Make sure that identifier is a valid shell identifier, i.e.
  2313.    does not contain a dollar sign, nor is quoted in any way.  Nor
  2314.    does it consist of all digits. */
  2315. check_identifier (word)
  2316.      WORD_DESC *word;
  2317. {
  2318.   if (word->dollar_present || word->quoted || all_digits (word->word))
  2319.     {
  2320.       report_error ("`%s' is not a valid identifier", word->word);
  2321.       return (0);
  2322.     }
  2323.   else
  2324.     return (1);
  2325. }
  2326.  
  2327. /* Return non-zero if all of the characters in STRING are digits. */
  2328. all_digits (string)
  2329.      char *string;
  2330. {
  2331.   while (*string)
  2332.     {
  2333.       if (!digit (*string))
  2334.     return (0);
  2335.       else
  2336.     string++;
  2337.     }
  2338.   return (1);
  2339. }
  2340.  
  2341. #define u_mode_bits(x) (((x) & 0000700) >> 6)
  2342. #define g_mode_bits(x) (((x) & 0000070) >> 3)
  2343. #define o_mode_bits(x) (((x) & 0000007) >> 0)
  2344. #define X_BIT(x) (x & 1)
  2345.  
  2346. /* Non-zero if the last call to executable_file () found
  2347.    the file, but stated that it wasn't executable. */
  2348. int file_exists_p = 0;
  2349.  
  2350. /* Return some flags based on information about this file.
  2351.    The EXISTS bit is non-zero if the file is found.
  2352.    The EXECABLE bit is non-zero the file is executble.
  2353.    Zero is returned if the file is not found. */
  2354. int
  2355. file_status (name)
  2356.      char *name;
  2357. {
  2358.   struct stat finfo;
  2359.   static int user_id = -1;
  2360.  
  2361.   /* Determine whether this file exists or not. */
  2362.   if (stat (name, &finfo) < 0)
  2363.     return (0);
  2364.  
  2365.   /* If the file is a directory, then it is not "executable" in the
  2366.      sense of the shell. */
  2367.   if (S_ISDIR (finfo.st_mode))
  2368.     return (FS_EXISTS);
  2369.  
  2370.   /* Find out if the file is actually executable.  By definition, the
  2371.      only other criteria is that the file has an execute bit set that
  2372.      we can use. */
  2373.   if (user_id == -1)
  2374.     user_id = geteuid ();
  2375.  
  2376.   /* Root only requires execute permission for any of owner, group or
  2377.      others to be able to exec a file. */
  2378.   if (user_id == 0)
  2379.     {
  2380.       int bits;
  2381.  
  2382.       bits = (u_mode_bits (finfo.st_mode) |
  2383.           g_mode_bits (finfo.st_mode) |
  2384.           o_mode_bits (finfo.st_mode));
  2385.  
  2386.       if (X_BIT (bits))
  2387.     return (FS_EXISTS | FS_EXECABLE);
  2388.     }
  2389.  
  2390.   /* If we are the owner of the file, the owner execute bit applies. */
  2391.   if (user_id == finfo.st_uid && X_BIT (u_mode_bits (finfo.st_mode)))
  2392.     return (FS_EXISTS | FS_EXECABLE);
  2393.  
  2394.   /* If we are in the owning group, the group permissions apply. */
  2395.   if (group_member (finfo.st_gid) && X_BIT (g_mode_bits (finfo.st_mode)))
  2396.     return (FS_EXISTS | FS_EXECABLE);
  2397.  
  2398.   /* If `others' have execute permission to the file, then so do we,
  2399.      since we are also `others'. */
  2400.   if (X_BIT (o_mode_bits (finfo.st_mode)))
  2401.     return (FS_EXISTS | FS_EXECABLE);
  2402.   else
  2403.     return (FS_EXISTS);
  2404. }
  2405.  
  2406. /* Return non-zero if FILE exists and is executable.
  2407.    Note that this function is the definition of what an
  2408.    executable file is; do not change this unless YOU know
  2409.    what an executable file is. */
  2410. int
  2411. executable_file (file)
  2412.      char *file;
  2413. {
  2414.   if (file_status (file) & FS_EXECABLE)
  2415.     return (1);
  2416.   else
  2417.     return (0);
  2418. }
  2419.  
  2420. /* DOT_FOUND_IN_SEARCH becomes non-zero when find_user_command ()
  2421.    encounters a `.' as the directory pathname while scanning the
  2422.    list of possible pathnames; i.e., if `.' comes before the directory
  2423.    containing the file of interest. */
  2424. int dot_found_in_search = 0;
  2425.  
  2426. /* Locate the executable file referenced by NAME, searching along
  2427.    the contents of the shell PATH variable.  Return a new string
  2428.    which is the full pathname to the file, or NULL if the file
  2429.    couldn't be found.  If a file is found that isn't executable,
  2430.    and that is the only match, then return that. */
  2431. char *
  2432. find_user_command (name)
  2433.      char *name;
  2434. {
  2435.   return (find_user_command_internal (name, FS_EXEC_PREFERRED));
  2436. }
  2437.  
  2438. /* Locate the file referenced by NAME, searching along the contents
  2439.    of the shell PATH variable.  Return a new string which is the full
  2440.    pathname to the file, or NULL if the file couldn't be found.  This
  2441.    returns the first file found. */
  2442. char *
  2443. find_path_file (name)
  2444.      char *name;
  2445. {
  2446.   return (find_user_command_internal (name, FS_EXISTS));
  2447. }
  2448.  
  2449. static char *
  2450. find_user_command_internal (name, flags)
  2451.      char *name;
  2452.      int flags;
  2453. {
  2454.   char *path_list;
  2455.  
  2456.   path_list = get_string_value ("PATH");
  2457.  
  2458.   if (!path_list)
  2459.     return (savestring (name));
  2460.  
  2461.   return (find_user_command_in_path (name, path_list, flags));
  2462. }
  2463.  
  2464. char *
  2465. user_command_matches (name, flags, state)
  2466.      char *name;
  2467.      int flags, state;
  2468. {
  2469.   register int i;
  2470.   char *path_list;
  2471.   int  path_index;
  2472.   char *path_element;
  2473.   char *match;
  2474.   static char **match_list = NULL;
  2475.   static int match_list_size = 0;
  2476.   static int match_index = 0;
  2477.   char *extract_colon_unit ();
  2478.  
  2479.   if (!state)
  2480.     {
  2481.       /* Create the list of matches. */
  2482.       if (!match_list)
  2483.     {
  2484.       match_list =
  2485.         (char **) xmalloc ((match_list_size = 5) * sizeof(char *));
  2486.  
  2487.       for (i = 0; i < match_list_size; i++)
  2488.         match_list[i] = 0;
  2489.     }
  2490.  
  2491.       /* Clear out the old match list. */
  2492.       for (i = 0; i < match_list_size; i++)
  2493.     match_list[i] = NULL;
  2494.  
  2495.       /* We haven't found any files yet. */
  2496.       match_index = 0;
  2497.  
  2498.       path_list = get_string_value ("PATH");
  2499.       path_index = 0;
  2500.  
  2501.       while (path_element = extract_colon_unit (path_list, &path_index))
  2502.     {
  2503.       char *find_user_command_in_path ();
  2504.  
  2505.       match =
  2506.         find_user_command_in_path (name, path_element, flags);
  2507.  
  2508.       free (path_element);
  2509.  
  2510.       if (!match)
  2511.         continue;
  2512.  
  2513.       if (match_index + 1 == match_list_size)
  2514.         match_list = (char **)xrealloc
  2515.           (match_list, ((match_list_size += 10) + 1) * sizeof (char *));
  2516.       match_list[match_index++] = match;
  2517.       match_list[match_index] = (char *)NULL;
  2518.     }
  2519.  
  2520.       /* We haven't returned any strings yet. */
  2521.       match_index = 0;
  2522.     }
  2523.  
  2524.   match = match_list[match_index];
  2525.  
  2526.   if (match)
  2527.     match_index++;
  2528.  
  2529.   return (match);
  2530. }
  2531.  
  2532. /* Return 1 if PATH1 and PATH2 are the same file.  This is kind of
  2533.    expensive.  If non-NULL STP1 and STP2 point to stat structures
  2534.    corresponding to PATH1 and PATH2, respectively. */
  2535. int
  2536. same_file (path1, path2, stp1, stp2)
  2537.      char *path1, *path2;
  2538.      struct stat *stp1, *stp2;
  2539. {
  2540.   struct stat st1, st2;
  2541.  
  2542.   if (stp1 == NULL)
  2543.     {
  2544.       if (stat (path1, &st1) != 0)
  2545.     return (0);
  2546.       stp1 = &st1;
  2547.     }
  2548.  
  2549.   if (stp2 == NULL)
  2550.     {
  2551.       if (stat (path2, &st2) != 0)
  2552.     return (0);
  2553.       stp2 = &st2;
  2554.     }
  2555.  
  2556.   return ((stp1->st_dev == stp2->st_dev) && (stp1->st_ino == stp2->st_ino));
  2557. }
  2558.  
  2559. /* This does the dirty work for find_path_file () and find_user_command ().
  2560.    NAME is the name of the file to search for.
  2561.    PATH_LIST is a colon separated list of directories to search.
  2562.    FLAGS contains bit fields which control the files which are eligible.
  2563.    Some values are:
  2564.       FS_EXEC_ONLY:        The file must be an executable to be found.
  2565.       FS_EXEC_PREFERRED:    If we can't find an executable, then the
  2566.                 the first file matching NAME will do.
  2567.       FS_EXISTS:        The first file found will do.
  2568. */
  2569. static char *
  2570. find_user_command_in_path (name, path_list, flags)
  2571.      char *name;
  2572.      char *path_list;
  2573.      int flags;
  2574. {
  2575.   extern char *extract_colon_unit ();
  2576.   extern int file_exists_p;
  2577.   char *full_path, *path, *file_to_lose_on;
  2578.   int status, path_index, name_len;
  2579.   struct stat finfo;
  2580.  
  2581.   name_len = strlen (name);
  2582.  
  2583.   /* The file name which we would try to execute, except that it isn't
  2584.      possible to execute it.  This is the first file that matches the
  2585.      name that we are looking for while we are searching $PATH for a
  2586.      suitable one to execute.  If we cannot find a suitable executable
  2587.      file, then we use this one. */
  2588.   file_to_lose_on = (char *)NULL;
  2589.  
  2590.   /* We haven't started looking, so we certainly haven't seen
  2591.      a `.' as the directory path yet. */
  2592.   dot_found_in_search = 0;
  2593.  
  2594.   if (absolute_program (name))
  2595.     {
  2596.       full_path = (char *)xmalloc (1 + name_len);
  2597.       strcpy (full_path, name);
  2598.  
  2599.       status = file_status (full_path);
  2600.  
  2601.       if (!(status & FS_EXISTS))
  2602.     return (0);
  2603.  
  2604.       if ((flags & FS_EXEC_ONLY) && (status & FS_EXECABLE))
  2605.     return (full_path);
  2606.       else
  2607.     {
  2608.       free (full_path);
  2609.       return ((char *)NULL);
  2610.     }
  2611.     }
  2612.  
  2613.   /* Find out the location of the current working directory. */
  2614.   stat (".", &finfo);
  2615.  
  2616.   path_index = 0;
  2617.   while (path_list && path_list[path_index])
  2618.     {
  2619.       path = extract_colon_unit (path_list, &path_index);
  2620.  
  2621.       if (!path || !*path)
  2622.     {
  2623.       if (path)
  2624.         free (path);
  2625.  
  2626.       path = savestring ("."); /* By definition. */
  2627.     }
  2628.  
  2629.       if (*path == '~')
  2630.     {
  2631.       char *tilde_expand ();
  2632.       char *t = tilde_expand (path);
  2633.       free (path);
  2634.       path = t;
  2635.     }
  2636.  
  2637.       /* Remember the location of "." in the path, in all its forms
  2638.      (as long as they begin with a `.', e.g. `./.') */
  2639.       if ((*path == '.') &&
  2640.       same_file (".", path, &finfo, (struct stat *)NULL))
  2641.     dot_found_in_search = 1;
  2642.  
  2643.       full_path = (char *)xmalloc (2 + strlen (path) + name_len);
  2644.       sprintf (full_path, "%s/%s", path, name);
  2645.       free (path);
  2646.  
  2647.       status = file_status (full_path);
  2648.  
  2649.       if (!(status & FS_EXISTS))
  2650.     goto next_file;
  2651.  
  2652.       /* The file exists.  If the caller simply wants the first file,
  2653.      here it is. */
  2654.       if (flags & FS_EXISTS)
  2655.     return (full_path);
  2656.  
  2657.        /* If the file is executable, then it satisfies the cases of
  2658.       EXEC_ONLY and EXEC_PREFERRED.  Return this file unconditionally. */
  2659.       if (status & FS_EXECABLE)
  2660.     {
  2661.       if (file_to_lose_on)
  2662.         free (file_to_lose_on);
  2663.  
  2664.       return (full_path);
  2665.     }
  2666.  
  2667.       /* The file is not executable, but it does exist.  If we prefer
  2668.      an executable, then remember this one if it is the first one
  2669.      we have found. */
  2670.       if (flags & FS_EXEC_PREFERRED)
  2671.     {
  2672.       if (!file_to_lose_on)
  2673.         file_to_lose_on = savestring (full_path);
  2674.     }
  2675.  
  2676.     next_file:
  2677.       free (full_path);
  2678.     }
  2679.  
  2680.   /* We didn't find exactly what the user was looking for.  Return
  2681.      the contents of FILE_TO_LOSE_ON which is NULL when the search
  2682.      required an executable, or non-NULL if a file was found and the
  2683.      search would accept a non-executable as a last resort. */
  2684.   return (file_to_lose_on);
  2685. }
  2686.  
  2687. /* Given a string containing units of information separated by colons,
  2688.    return the next one pointed to by INDEX, or NULL if there are no more.
  2689.    Advance INDEX to the character after the colon. */
  2690. char *
  2691. extract_colon_unit (string, index)
  2692.      char *string;
  2693.      int *index;
  2694. {
  2695.   int i, start;
  2696.  
  2697.   i = *index;
  2698.  
  2699.   if (!string || (i >= strlen (string)))
  2700.     return ((char *)NULL);
  2701.  
  2702.   /* Each call to this routine leaves the index pointing at a colon if
  2703.      there is more to the path.  If I is > 0, then increment past the
  2704.      `:'.  (If I is 0, then the path has a leading colon.  If this is
  2705.      not done, the second call to this routine will always return NULL,
  2706.      which will be translated to  `.', even if `.' is not in the path.
  2707.      Trailing colons are handled OK by the `else' part of the if
  2708.      statement; it returns an empty string for the last component of a
  2709.      path with a trailing colon, and the routines that call this will
  2710.      translate that to `.'. */
  2711.  
  2712.   if (i && string[i] == ':')
  2713.     i++;
  2714.  
  2715.   start = i;
  2716.  
  2717.   while (string[i] && string[i] != ':') i++;
  2718.  
  2719.   *index = i;
  2720.  
  2721.   if (i == start)
  2722.     {
  2723.       if (!string[i])
  2724.     return ((char *)NULL);
  2725.  
  2726.       (*index)++;
  2727.  
  2728.       return (savestring (""));
  2729.     }
  2730.   else
  2731.     {
  2732.       char *value;
  2733.  
  2734.       value = (char *)xmalloc (1 + (i - start));
  2735.       strncpy (value, &string[start], (i - start));
  2736.       value [i - start] = '\0';
  2737.  
  2738.       return (value);
  2739.     }
  2740. }
  2741.  
  2742. /* Return non-zero if the characters from SAMPLE are not all valid
  2743.    characters to be found in the first line of a shell script.  We
  2744.    check up to the first newline, or SAMPLE_LEN, whichever comes first.
  2745.    All of the characters must be printable or whitespace. */
  2746.  
  2747. #if !defined (isspace)
  2748. #define isspace(c) ((c) == ' ' || (c) == '\t' || (c) == '\n' || (c) == '\f')
  2749. #endif
  2750.  
  2751. #if !defined (isprint)
  2752. #define isprint(c) (isletter(c) || digit(c) || ispunct(c))
  2753. #endif
  2754.  
  2755. int
  2756. check_binary_file (sample, sample_len)
  2757.      unsigned char *sample;
  2758.      int sample_len;
  2759. {
  2760.   register int i;
  2761.  
  2762.   for (i = 0; i < sample_len; i++)
  2763.     {
  2764.       if (sample[i] == '\n')
  2765.     break;
  2766.  
  2767.       if (!isspace (sample[i]) && !isprint (sample[i]))
  2768.     return (1);
  2769.     }
  2770.   return (0);
  2771. }
  2772.